# -*- coding:utf-8 -*-
import configparser
import os


class IniUtil:
    # 根目录下的config.ini文件路径
    _current_dir = os.path.dirname(os.path.abspath(__file__))  # 获取当前文件的目录
    _config_file_path = os.path.join(_current_dir, 'config.ini')  # 构建完整的绝对路径
    _config = None

    _section = None

    def __init__(self, path=''):
        if path:
            self._config_file_path = path
        print(f'==>> 配置路径:{self._config_file_path}')
        # 实例化
        self._config = configparser.ConfigParser()
        # 读取配置内容
        self._config.read(self._config_file_path, encoding="utf-8-sig")

    def group(self, section='default'):
        """ 指定配置分组名称

        :return: self
        """
        self._section = section
        return self

    def get_group_all(self, section=None) -> dict:
        """ 获取指定配置分组下所有配置

        :param section: 配置分组名称
        :return: dict
        """
        if section is None:
            section = self._section

        list_key = self._config.options(section)
        items = {}
        for item_key in list_key:
            items[item_key] = self._config.get(section, item_key)
        return items

    def get_all(self) -> dict:
        """ 获取所有配置

        :return: dict
        """
        _sections = self._config.sections()
        _data = {}
        for section in _sections:
            group_sect = self._config.options(section)
            if section not in _data:
                _data[section] = {}

            for key in group_sect:
                _data[section][key] = self._config.get(section, key)

        return _data

    def get(self, section=None, key=None, fallback=None) -> str:
        """
        获取配置key值
        :param section:
        :param key: 配置名称
        :param fallback: 找不到配置项时的默认值
        :return: any
        """
        if not section:
            section = self._section
        return self._config.get(section, key, fallback=fallback)



